<template>
  <el-row>
    <el-col :sm="{span:10,offset:7}">
      <el-form :model="type" :rules="rules" class="margin_bt" ref="typeForm" label-width="80px">
        <el-form-item label="分类名称" prop="name">
            <el-input v-model="type.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="type.color"></el-color-picker>
        </el-form-item>
        <el-form-item class="center">
          <el-button type="primary" @click="submit('typeForm')">添加</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import axios from 'axios'
import {ElMessage} from 'element-plus'
export default {
  name: "addTypes",
  data() {
    return{
      type: {
        name: '',
        color: '#00ff98',
        md5Password: ''
      },
      rules: {
        name: [
          { required:true,message:'请输入分类名称',trigger: 'blur'}
        ]
      }
    }
  },
  mounted(){
    let id = this.$route.query.id;
    if ( id != undefined) {
      axios.get("/admin/selectOneType",{params:{id:id}}).then( (res) => {
        this.type = res.data
      })
    }
  },
  methods: {
    submit: function (typeForm){
       this.$refs[typeForm].validate( (valid) => {
         if ( valid ){
            this.type.md5Password = localStorage.getItem("password");
            if ( this.$route.query.id === undefined){
                axios.post("/admin/insertType",this.type).then( (res) => {
                  if ( res.data === true){
                    ElMessage.success("添加成功")
                    this.$router.push({
                      name: 'types'
                    })
                  }
                  else
                    ElMessage.error("添加失败")
                })
            }
            else {
              axios.post("/admin/updateType", this.type).then((res) => {
                if (res.data === true) {
                  ElMessage.success("修改成功");
                  this.$router.push({
                    name: 'types'
                  })
                } else {
                  ElMessage.error("修改失败")
                }
              })
            }
         }else {
           console.log("失败")
         }
       })
    }
  }
}
</script>

<style scoped>
.center {
  text-align: center;
}
.margin_bt {
  margin: 50px 0;
}
</style>